import { ReactElement, useEffect, useState, useImperativeHandle, forwardRef, Ref } from 'react'
import { Skeleton, Menu, Dropdown, Button, Modal } from 'antd'
import style from './index.module.less'
import { getTreeRequest, TreeSchema, deleteRequest } from './ajax'
import { EllipsisOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { awaitWrap } from '@js/tool'
import Tree, { TreeData } from '@components/tree'
import classNames from 'classnames'
import EditModal from './components/editModal'
import EditTypeModal from './components/editTypeModal'
import { WorkPerformanceSchema } from '@components/schema/performanceSchema'

const { confirm } = Modal

// 从树中获取人员列表
function getWorkFromTree (d: TreeSchema[]): WorkPerformanceSchema[] {
  let res: WorkPerformanceSchema[] = []
  d.forEach(li => {
    if (li.type === 'account') {
      res.push(li.originData)
    }
    const list = li.children instanceof Array ? li.children : []
    res = [...res, ...getWorkFromTree(list)]
  })
  return res
}

async function initTree (performanceid: string, setTreeData: (v: TreeSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getTreeRequest(performanceid))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setTreeData(d)
  }
}

function confrimDelete (performanceid: string, id: string, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确认要删除吗？',
    onOk: () => {
      deleteHandle(performanceid, id, refreshData).catch(e => console.error(e))
    }
  })
}

async function deleteHandle (performanceid: string, id: string, refreshData: () => void): Promise<void> {
  const [e] = await awaitWrap(deleteRequest(performanceid, id))
  if (e === null) {
    refreshData()
  }
}

function renderTreeNode (data: TreeData, clickHandle: (v: WorkPerformanceSchema) => void, current: WorkPerformanceSchema | null, performanceid: string, refreshData: () => void, setModifyData: (v: WorkPerformanceSchema) => void, setVisible: (v: boolean) => void): ReactElement {
  if (data.type === 'department') {
    return (
      <div className={style['leaf-line']}>
        <span>{data.title}</span>
      </div>
    )
  }
  const d = (data as TreeSchema).originData
  const type: string = typeof d === 'object' && d !== null && typeof d.employee_type_desc === 'string' ? d.employee_type_desc : ''
  const menu = (
    <Menu>
      <Menu.Item>
        <a onClick={() => { setModifyData(d); setVisible(true) }}>修改考核类别</a>
        <a onClick={() => confrimDelete(performanceid, d.id as string, refreshData)}>删除</a>
      </Menu.Item>
    </Menu>
  )
  return (
    <div className={style['leaf-line']}>
      <span className={classNames(style['leaf-name'], { [style.active]: current !== null && current.id === data.key })} onClick={() => clickHandle(d)}>
        {data.title}{type.length > 0 ? <span className={style['leaf-subtitle']}>{type}</span> : ''}
      </span>
      <Dropdown overlay={menu} trigger={['click']}>
        <a className={style['leaf-icon']}><EllipsisOutlined /></a>
      </Dropdown>
    </div>
  )
}

export interface PersonRef {
  refreshData: () => void
}

interface Props {
  performanceid: string
  current: WorkPerformanceSchema | null
  setCurrent: (v: WorkPerformanceSchema | null) => void
}

function Main ({ performanceid, current, setCurrent }: Props, ref: Ref<PersonRef>): ReactElement {
  const [treeData, setTreeData] = useState<TreeSchema[]>([])
  const [loading, setLoading] = useState(false)
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<WorkPerformanceSchema | null>(null)
  const [typeVisible, setTypeVisible] = useState(false)
  function refreshFn (): void { initTree(performanceid, setTreeData, setLoading).catch(e => console.error(e)) }
  useEffect(() => {
    refreshFn()
  }, [])
  useEffect(() => {
    const list = getWorkFromTree(treeData)
    const ids = list.map(li => li.id)
    if (list.length > 0) {
      if (current !== null) {
        const index = ids.indexOf(current.id)
        if (index !== -1) {
          setCurrent(list[index])
        } else {
          setCurrent(list[0])
        }
      } else {
        setCurrent(list[0])
      }
    }
  }, [treeData])
  useImperativeHandle(ref, () => {
    return {
      refreshData: refreshFn
    }
  })
  return (
    <div className={style.container}>
      <EditModal visible={visible} data={modifyData} performanceid={performanceid} hide={() => { setModifyData(null); setVisible(false) }} refreshData={refreshFn} />
      <EditTypeModal visible={typeVisible} data={modifyData} performanceid={performanceid} hide={() => { setModifyData(null); setTypeVisible(false) }} refreshData={refreshFn} />
      <div className={style.btn}>
        <Button type='primary' block size='large' disabled={loading} onClick={() => { setModifyData(null); setVisible(true) }}>添加人员</Button>
      </div>
      <div className={style.list}>
        <Skeleton loading={loading} active>
          <Tree treeData={treeData} defaultExpandAll renderNode={(data) => renderTreeNode(data, (d: WorkPerformanceSchema) => setCurrent(d), current, performanceid, refreshFn, setModifyData, setTypeVisible)} onClick={(d) => setCurrent((d as TreeSchema).originData)} />
        </Skeleton>
      </div>
    </div>
  )
}

export default forwardRef(Main)
